package second.backtracking;

import java.util.ArrayList;
import java.util.List;

public class Solution07 {
    List<List<Integer>> res;
    
    List<Integer> tmp;
    int sum = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        res = new ArrayList<>();
        tmp = new ArrayList<>();
        back(candidates, target, 0);
        return res;
    }
    
    public void back(int[] candidates, int target, int index) {
        if (sum > target) return;
        if (sum == target) {
            res.add(new ArrayList<>(tmp));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            tmp.add(candidates[i]);
            sum += candidates[i];
            back(candidates, target, i);
            sum -= candidates[i];
            tmp.remove(tmp.size() - 1);
        }
    }
}
